package lucius.work.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Repository;

import lucius.work.dao.*;
import lucius.work.entity.*;

@Repository("bookDao")
public class BookDaoImpl extends BaseDao<Book> implements BookDao{

	@SuppressWarnings("unchecked")
	@Override
	public List<book> findByPage(final int page, final int pageSize) {

		return (List<book>) getHibernateTemplate().execute(new HibernateCallback<Object>() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException {

				String hql = "from book";
				Query query = session.createQuery(hql);
				/*
				 * 设置分页参数，注意在内层函数中调用外层函数的参数， 要求外层函数的参数必须是final的，因此需要将
				 * page、pageSize设置为final。
				 */
				query.setFirstResult((page - 1) * pageSize);
				query.setMaxResults(pageSize);
				return query.list();

			}

		});
	}

	@Override
	public int findTotalPage(int pageSize) {

		String hql = "select count(*) from book";
		List<book> list = find(hql);
		// 查询出总行数
		int rows = list.size();
		// 根据总行数计算出总页数
		if (rows % pageSize == 0) {
			return rows / pageSize;

		} else {
			return rows / pageSize + 1;

		}
	}

}
